<template>
  <div class="app-container">
    <el-form inline size="mini" :model="queryParams">
      <el-form-item label="部门名称">
        <el-input v-model.trim="queryParams.dept_name" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" clearable>
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onGetTableData">查询</el-button>
        <el-button size="mini" @click="onResetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="2">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-plus"
          @click="onOpenAddDeptModal"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" max-height="500" :data="tableData" row-key="dept_id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="部门名称" prop="dept_name" />
      <el-table-column label="排序" prop="order_num" align="center" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status === "0" ? '正常' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="onOpenModifyDeptModal(scope.$index, scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="onOpenAddDeptModal(scope.$index, scope.row)">新增</el-button>
          <el-button type="text" size="small" @click="onDeleteDept(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加或修改岗位信息-->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="deptForm" :model="deptForm" :rules="deptFormRules" label-width="80px">
        <el-row v-if="deptForm.parent_id !== 0">
          <el-col>
            <el-form-item prop="parent_id" label="上级部门">
              <treeselect v-model="deptForm.parent_id" :normalizer="normalizer" placeholder="请选择上级部门" :options="deptTree" :show-count="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="dept_name" label="部门名称">
              <el-input v-model="deptForm.dept_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="order_num" label="显示排序">
              <el-input-number v-model="deptForm.order_num" style="width: 100%;" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input v-model="deptForm.leader" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="phone" label="联系电话">
              <el-input v-model="deptForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="deptForm.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="deptForm.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="open = false">取 消</el-button>
        <el-button size="small" type="primary" @click="onAddOrModifyDept">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import { getDeptListApi, addDeptApi, modifyDeptApi, deleteDeptApi } from '@/api/dept'
import { obj2newField, toTreeAndMap } from '@/utils'
export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    return {
      queryParams: {},
      loading: false,
      // 表格数据
      tableData: [],

      title: '',
      open: false,
      deptForm: {},
      deptFormRules: {
        parent_id: [
          { required: true, message: '上级部门不能为空', trigger: 'blur' }
        ],
        dept_name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        order_num: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },

      deptTree: [],
      normalizer(node) {
        return {
          id: node.dept_id,
          label: node.dept_name,
          children: node.children
        }
      }
    }
  },
  created() {
    this.onGetTableData()
  },
  methods: {
    /**
     * 重置查询条件
     */
    onResetQuery() {
      this.queryParams = {
        dept_name: undefined,
        status: undefined
      }
      this.$resetForm('queryParams')
      this.onGetTableData()
    },

    /**
     * 获取部门列表
     */
    onGetTableData() {
      this.loading = true
      const params = {
        ...this.queryParams
      }
      getDeptListApi(params).then((res) => {
        this.loading = false
        if (res && res.code === 0) {
          const list_arr = res.data.map(item => obj2newField(item, { dept_id: 'id', dept_name: 'label' }))

          const { treeData } = toTreeAndMap(list_arr, 'dept_id', 'parent_id')

          // const list = toTreeByRecursion(list_arr, 'dept_id', 'parent_id', 0, 'children')
          this.tableData = treeData
        }
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 重置部门添加或修改表单
     */
    resetDeptForm() {
      this.deptForm = {
        dept_id: undefined,
        parent_id: undefined,
        dept_name: undefined,
        order_num: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: 0
      }
      this.$resetForm('deptForm')
    },

    /**
     * 打开新增部门弹窗
     * @param index 当前索引
     * @param row 当前部门数据
     */
    onOpenAddDeptModal(index, row) {
      this.resetDeptForm()
      this.onGetDeptTreeData()
      if (row) {
        this.deptForm.parent_id = row.dept_id
      }
      this.title = '新建部门'
      this.open = true
    },

    /**
     * 打开修改部门弹窗
     * @param index 当前索引
     * @param row 当前部门数据
     */
    onOpenModifyDeptModal(index, dept) {
      this.resetDeptForm()
      this.onGetDeptTreeData()
      this.deptForm = {
        ...dept,
        status: +dept.status
      }
      this.title = '修改部门'
      this.open = true
    },

    /**
     * 获取部门tree数据
     */
    onGetDeptTreeData() {
      getDeptListApi({}).then((res) => {
        if (res && res.code === 0) {
          const { treeData } = toTreeAndMap(res.data, 'dept_id', 'parent_id')
          this.deptTree = treeData
        }
      })
    },

    /**
     * 新增或修改部门信息
     */
    onAddOrModifyDept() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          const params = {
            dept_id: this.deptForm.dept_id,
            parent_id: this.deptForm.parent_id,
            dept_name: this.deptForm.dept_name,
            order_num: this.deptForm.order_num,
            status: this.deptForm.status,
            leader: this.deptForm.leader,
            phone: this.deptForm.phone,
            email: this.deptForm.email
          }

          // 新增部门
          if (this.deptForm.dept_id === undefined) {
            addDeptApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            // 修改部门
            modifyDeptApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },

    // 删除部门数据
    onDeleteDept(index, dept) {
      this.$confirm('确认删除当前部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          dept_id: dept.dept_id
        }
        deleteDeptApi(params).then((res) => {
          if (res && res.code === 0) {
            this.$message.success(res.msg)
            this.onGetTableData()
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
